var user = '';
var query = '';
var links = [];
var stat = 2;
var used = 0;
var totalFriends = [];
var upVoteFlag = 0;
var twitterName = '';
var storeLinks = [];
var isVoteCasted=false;
var siteUrl = '';
var receiveMessage = "";
var fbFriends = '';
var twitterFriends = '';
var gapiName = '';
var gapiFriends = '';
var _wow = 'wow';
var host = 'softctrl.in';
var softhost='softctrl.in';
var isFbAvailable;
var isGapiAvailable;
var isTwAvailable;
var isFbApplied;
var isGapiApplied;
var isTwApplied;
var isNonFriendApplied;
var currentLinks='';
var GAPI_CONSTANT_FRIENDS = 'ExGapiFriends';
var FB_CONSTANT_FRIENDS = 'ExFbFriends';
var TW_CONSTANT_FRIENDS = 'ExTwFriends';
var FB_CONSTANT_NAME = 'ExFbName';
var TW_CONSTANT_NAME = 'ExTwName';
var GAPI_CONSTANT_NAME = 'ExGapiName';
var SL='sl'
var GAPI = 'Gapi';
var FB = 'Fb';
var TW = 'Tw';
var upVoteQuery = '';
var isGapiLocalStoreAvailable = false;
var isFbLocalStoreAvailable = false;
var isTwLocalStoreAvailable = false;
var isGapiSelfStoreAvailable = false;
var isFbSelfStoreAvailable = false;
var isTwSelfStoreAvailable = false;

var foo = document.getElementById('search');
var isScriptCalled = false;
var fbUserName = '';
var gapiUserName = '';
var sessionMap;
var CONSTANT_STOREMAP = 'storeMap';
var twUserName = '';
var isIdentityDivCreated = false;
var isSearchElementCreated = false;
var mutationObserverTimer;
var gotNonFriendLinkUpVotes = false;
var _all = "all";

function KeyPress(e) {
	var evtobj = window.event? event : e
			if (evtobj.keyCode == 76 && evtobj.altKey) 
			{
				if(divFlag!=1)
				{
					upVote('facebook');
					upVote('twitter');
					upVote('gmail');
				}
			}
}


function checkApplication() {
	if (!isFbApplied) {
		addiFrames(true, false, false);
	} else if (!isTwApplied) {
		addiFrames(false, true, false);
	} else if (!isGapiApplied) {
		addiFrames(false, false, true);
	}

	else {
		isFbAvailable = false;
		isGapiAvailable = false;
		isTwAvailable = false;
		isFbApplied = false;
		isGapiApplied = false;
		isTwApplied = false;
	}
}
function createIdentityDiv() {
	var el = document.createElement("div");
	el.id = "frinser_identity";
	el.style.marginLeft = "127px";

	var fbIdentityDiv = document.createElement("div");
	fbIdentityDiv.id = "frinser_fbIdentityDiv";
	var fbIframeIdentityDiv = document.createElement("iframe");
	fbIframeIdentityDiv.setAttribute("src",
			"https://softctrl.in/public/fbIdentityDiv.html");
	fbIframeIdentityDiv.setAttribute("scrolling", "no");
	fbIframeIdentityDiv.style.border = "none";
	fbIframeIdentityDiv.style.width = "250px";
	fbIframeIdentityDiv.style.height = "50px";
	fbIdentityDiv.appendChild(fbIframeIdentityDiv);
	fbIdentityDiv.style.cssFloat = "left";
	el.appendChild(fbIdentityDiv);

	var gapiIdentityDiv = document.createElement("div");
	gapiIdentityDiv.id = "frinser_gapiIdentityDiv";
	var gapiIframeIdentityDiv = document.createElement("iframe");
	gapiIframeIdentityDiv.setAttribute("src",
			"https://softctrl.in/public/gapiIdentityDiv.html");
	gapiIframeIdentityDiv.setAttribute("scrolling", "no");
	gapiIframeIdentityDiv.style.border = "none";
	gapiIframeIdentityDiv.style.width = "250px";
	gapiIframeIdentityDiv.style.height = "50px";
	gapiIframeIdentityDiv.style.cssFloat = "left";
	gapiIdentityDiv.appendChild(gapiIframeIdentityDiv);
	el.appendChild(gapiIdentityDiv);

	var twiiterIdentityDiv = document.createElement("div");
	twiiterIdentityDiv.id = "frinser_twitterIdentityDiv";
	var twitterIframeIdentityDiv = document.createElement("iframe");
	twitterIframeIdentityDiv.setAttribute("src",
			"https://softctrl.in/twitteroauth-master/twitterIdentityDiv.php");
	twitterIframeIdentityDiv.setAttribute("scrolling", "no");
	twitterIframeIdentityDiv.style.border = "none";
	twitterIframeIdentityDiv.style.width = "250px";
	twitterIframeIdentityDiv.style.height = "50px";
	twiiterIdentityDiv.appendChild(twitterIframeIdentityDiv);
	el.appendChild(twiiterIdentityDiv);

	var top_nav = document.getElementById("top_nav");
	if (top_nav != null) {
		insertAfter(top_nav, el);
		isIdentityDivCreated = true;
	}
}

//function mutationObserve() {
//	console.log("Starting mutationObserve: "
//			+ document.getElementById('search'));
//	var observer = new MutationObserver(function(mutations) {
//		// Notice this will not be called because takeRecords clears outstanding
//		// records
//		console.log('In MutationObserver callback');
////		if (!isScriptCalled) {
////			googleScript();
////		}
//
//	});
//	if (document.getElementById('search') != null
//			&& document.getElementById('search') != undefined
//			&& document.getElementById('search') != "") {
//		console.log("starting mutation observe");
//		observer.observe(document.getElementById('search'), {
//			childList : true,
//			subtree : true
//		});
////		googleScript();
//		isSearchElementCreated = true;
//		clearInterval(mutationObserverTimer);
//
//	}
//
//	var mutations = observer.takeRecords();
//
//	mutations.forEach(function(mutation) {
//		console.log('In MutationObserver forEach');
////		if (!isScriptCalled) {
////			googleScript();
////		}
//		for (var i = 0; i < mutation.addedNodes.length; i++) {
//			console.log('"' + mutation.addedNodes[i].textContent + '" added');
//		}
//	});
//}

// init chrome local storage if empty
function linksArrayCheckAndInit() {
	chrome.storage.local.get('links', function(result) {
		// console.log("chrome.storage.local.get.links: " +result.links);
		if (result.links == undefined) {
			chrome.storage.local.set({
				'links' : ''
			});
		}
	});
}

linksArrayCheckAndInit();

window.onresize = function() {
	toggle();
}

function toggle() {
	if (window.innerWidth < 900) {
		// document.getElementById('frinser_identity').style.display = 'none';
	} else {
		// document.getElementById('frinser_identity').style.display = 'block';
	}
}

//function createMutationObserver() {
//	console.log("createMutationObserver called");
//	if (document.getElementById('search') != null) {
//		if (!isSearchElementCreated) {
//			console.log("calling mutationObserve");
//			mutationObserve();
//		} else {
//			/* Mutation observer already created */
//			console.log("Mutation observer already created");
//		}
//	} else {
//		/* do nothing as search element is still null */
//		console.log("do nothing as search element is still null");
//	}
//}

if (document.title.indexOf("Google Search") != -1
		|| (location.href.indexOf('www.google') > -1)) {

	window.onhashchange = function() {
		isFbAvailable = false;
		isGapiAvailable = false;
		isTwAvailable = false;
		isFbApplied = false;
		isGapiApplied = false;
		isTwApplied = false;

		googleScriptCaller();
//		isScriptCalled = false;
//		{
//			googleScript();
//		}

	};
//  {
//		googleScript();
//	}
  googleScriptCaller();
//	console.log("setting mutation observer interval timer");
//
//	mutationObserverTimer = setInterval(createMutationObserver, 100);
} else {
	window.onbeforeunload = function() {
		console
				.log("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
		if (upVoteFlag == 1) {

			storeTimTaken('twitter');

		}

	};
	document.onkeydown = KeyPress;
	setUpNonGooogleLinks();
}
function isNewLinksLoaded()
{
	var newLinks='';
	var x = document.getElementsByTagName("h3");
		for (var i = 0; i < x.length; i++) {
			var a = x[i].innerHTML;
			if (a.indexOf('href') > -1) {

				var start = a.indexOf('href="') + 6;
				var end = a.substring(start, a.length).indexOf('" ') + start;
				var link = a.substring(start, end);
				if (link.indexOf('http') > -1) { // x[i].innerHTML= "<img
					link = normalizeLink(link);
					if (link.search('adurl=') == -1) {
					newLinks=newLinks+link;
					}
				}
			}// x[i].appendChild(a);

		}
	if(newLinks==currentLinks)
		{
		return false;
		}
	else
		{
		currentLinks=newLinks;
		return true;
		}

}
function googleScriptCaller()
{
	var linksLoad= setInterval(function(){ 
		if(isNewLinksLoaded())
		{
			clearInterval(linksLoad);
			googleScript();
		}
	}, 500);
}
function isChild(link, referer, store) {
	var storeJSON = JSON.parse(store);// [normalizeLink(document.URL)]
	// //alert(link + " " + storeJSON[normalizeLink(referer)] + " " + store);
	if (storeJSON[normalizeLink(referer)] != undefined) {
		siteUrl = normalizeLink(referer);
		return true
	} else
		return false;
}

function setUpNonGooogleLinks() {
	twitterName = '';
	gapiName = '';
	user = '';
	linksArrayCheckAndInit();
	var link = normalizeLink(document.URL);
	var referer = document.referrer;
	siteUrl = normalizeLink(document.URL);
	if (referer.indexOf('www.google.') > -1) {
		addiFrames(true, true, true);
		var flag = 0;
		window.addEventListener('message', function(e) {
			// console.log(e.data);
			var str = e.data + "";
			if (str.indexOf('twitt-name') > -1) {
				isTwAvailable = true;
				twitterName = str.substring(str.indexOf('twitt-name') + 10,
						str.length);
				console
						.log('ISHUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU '
								+ twitterName);
			}
			if (str.indexOf('twitt-frnds') > -1) {
				twitterFriends = str.substring(str.indexOf('twitt-frnds') + 11,
						str.length);
				console.log('ISHUUUUUUUUUUUUUUjkUUUUUUUUUUUUUUUUU '
						+ twitterFriends);
			}
			if (str.indexOf('gapi-name') > -1) {
				gapiName = str.substring(str.indexOf('gapi-name') + 9,
						str.length);
				if (str.search('user') > -1 || str.indexOf('twitt-name') > -1
						|| str.indexOf('gapi-name') > -1) {
					isVoted(siteUrl, user, gapiName);

				}
				console.log('GAPPPPPPPPPPPPPPPPPPPPPPmmmmPPPPPPPPPPPPPI '
						+ gapiName);
			}

			if (str.search('status') > -1) {
				console.log(str);
				if (str.search(-1) > -1) {
					stat = -1
					console.log('Please log in');
				}
				if (str.search(0) > -1) {
					stat = 0;
					console.log('Please allow the app');
				}

			}
			if (str.search('user') > -1) {
				var userJSON = str.split('=');
				user = userJSON[1];
			}
			if (str.search('user') > -1 || str.indexOf('twitt-name') > -1
					|| str.indexOf('gapi-name') > -1) {
				isVoted(siteUrl, user, gapiName);
			}

		});
	}

}
function addDialogBox() {
	document.getElementById("yes").onclick = function() {
		upVote('facebook');
		upVote('twitter');
		upVote('gmail');

	};
	document.getElementById("no").onclick = function() {
		downVote('facebook');
		downVote('twitter');
		downVote('gmail');

	};

}
function sendAjax(url, data) {
if(isVoteCasted)
	return;	
	isVoteCasted=true;
	var req = createRequest(); // defined above
	// Create the callback:
	req.onreadystatechange = function() {
		if (req.readyState != 4)
			return; // Not there yet
		if (req.status != 201) {
			return;
		}
		if (req.status == 500) {
			// alert("Some error Occured");
			return;
		}

		// Request successful, read the response
		var resp = req.responseText;
		// document.getElementById('yes').visibility="hidden;
		// document.getElementById('no').visibility=hidden;

		// ... and use it as needed by your app.
		// //alert(req.responseText);

		return req.responseText;
	}
	req.open("POST", url, true);
	req.setRequestHeader("Content-Type", "application/json");
	req.send(data);
}
function storeTimTaken(site) {

	// //alert("jj " + twitterName);
	// //alert(JSON.parse(result.links)[siteUrl]+" query "+query);
	// que
	window_unfocused(null);
	// alert(total_active_time+" TTY");
	var tty = total_active_time;// document.getElementById('activeTimeDiv').innerHTML;

	var j = '{"link":"' + siteUrl + '","facebook":"' + user + '", "twitter":"'
			+ twitterName + '","tty":"' + tty + '","gapi":"' + gapiName + '"}';
	chrome.runtime.sendMessage({
		sendAjax : j
	}, function(response) {
		console.log(response.farewell);
	});
}
function upVote(site, vote) {
	Vote(site, 1);
}
function downVote(site, vote) {
	Vote(site, 0);
}
function findNextQuery(url, mapString) {
	if (mapString.indexOf(url) > -1) {
		var urlIndex = mapString.indexOf(url);
		var startQueryIndex = mapString.indexOf(':"', urlIndex);
	}
}
function Vote(site, vote) {
	// alert("jj " + twitterName);
	
	
	linksArrayCheckAndInit();
	chrome.storage.local.get('links', function(result) {
		console.log(result.links);
		window_unfocused(null);
		var tty = total_active_time;// document.getElementById('activeTimeDiv').innerHTML;
		var linksMap = result.links;
		query = contains(linksMap, normalizeLink(document.URL));
		if (query == 'false') {
//			return;
			query = '';
			console.log("THE QUERY WAS EMPTY");
		}
		upVoteQuery = query;
		if (site == 'facebook') {
			sendAjax('https://' + host
					+ ':8443/extension/rest/extension/upVote', '{"link":"'
					+ siteUrl + '","user":"' + user + '","vote":"' + vote
					+ '","tty":"' + tty + '","query":"' + query + '"}');

		} else if (site == 'twitter') {
			if (twitterName == '' || twitterName == undefined) {
				console.log("Twitter rate limit exceeded");
			} else
				sendAjax('https://' + host
						+ ':8443/extension/rest/extension/upVote', '{"link":"'
						+ siteUrl + '","user":"' + twitterName + '","vote":"'
						+ vote + '","tty":"' + tty + '","query":"' + query
						+ '"}');
		} else if (site == 'gmail') {

			sendAjax('https://' + host
					+ ':8443/extension/rest/extension/upVote', '{"link":"'
					+ siteUrl + '","user":"' + gapiName + '","vote":"' + vote
					+ '","tty":"' + tty + '","query":"' + query + '"}');
		}

		var storedValueJSON = (result.links);
		upVoteFlag = 1;
		document.getElementById("my_div").style.visibility = "hidden";
		delete storedValueJSON[normalizeLink(document.URL)];
		var s = JSON.stringify(storedValueJSON).substring(1,
				JSON.stringify(storedValueJSON).length - 1);
		chrome.storage.local.set({
			'links' : '{' + s + '}'
		});

	});

}
var divFlag = 0;
function isVoted(link, user, gapiuser) {

	var rest = 'https://' + host + ':8443/extension/rest/extension/isVoted';
	// alert('URL '+link);
	var data = '{"link":"' + link + '","user":"' + user + '","twName":"'
			+ twitterName + '","gapiName":"' + gapiuser + '"}';
	var req = createRequest(); // defined above
	// Create the callback:
	req.onreadystatechange = function() {
		if (req.readyState != 4)
			return; // Not there yet
		if (req.status != 201) {
			return;
		}
		var resp = JSON.parse(req.responseText);
		// alert(resp.result);
		if (resp.result == '-1' && divFlag != 1) {
			addDialogBox();
			document.getElementById("my_div").style.visibility = "visible";
		} else {
			// dont add it now
			divFlag = 1;
			document.getElementById("my_div").style.visibility = "hidden";
		}
	}
	req.open("POST", rest, true);
	req.setRequestHeader("Content-Type", "application/json");
	req.send(data);
}

function googleScript() {
	setTimeout(function() {
		checkApplication()
	}, 3000);

	console
			.log("called googleScript googleScript googleScript googleScript googleScript ");
	isScriptCalled = true;

	/*
	 * var btn = document.createElement("BUTTON") btn.id = "show"; var t =
	 * document.createTextNode("Show"); btn.appendChild(t);
	 * document.body.appendChild(btn); document.getElementById("show").onclick =
	 * function() { showLinkStorage() }; var btn1 =
	 * document.createElement("BUTTON") btn1.id = "clear"; var t1 =
	 * document.createTextNode("Clear"); btn1.appendChild(t1);
	 * document.body.appendChild(btn1); document.getElementById("clear").onclick =
	 * function() { clearStorage() };
	 */

	if ((document.getElementById("gbqfq") == null)
			|| (document.getElementById("gbqfq") == undefined)) {
		/* Query element not created */
		query = null;
		isScriptCalled = false;
	} else {
		query = document.getElementById("gbqfq").value;
	}

	getLinksMap();
	console.log("called getLinksMap() : " + links);

	if (links == "") {
		console.log("links is still empty after calling googleScript");
	} else {
		/*
		 * if(!getLinksMap()) { console.log("got false from getLinksMap");
		 * return; }
		 */

		if (localStorage.getItem(GAPI_CONSTANT_FRIENDS) != null
				&& localStorage.getItem(GAPI_CONSTANT_FRIENDS) != "") {
			getUpvotedLinksByType(GAPI);
		}
		if (localStorage.getItem(FB_CONSTANT_FRIENDS) != null
				&& localStorage.getItem(FB_CONSTANT_FRIENDS) != "") {
			getUpvotedLinksByType(FB);
		}
		if (localStorage.getItem(TW_CONSTANT_FRIENDS) != null
				&& localStorage.getItem(TW_CONSTANT_FRIENDS) != "") {
			getUpvotedLinksByType(TW);
		}
		if (localStorage.getItem(FB_CONSTANT_NAME) != null
				&& localStorage.getItem(FB_CONSTANT_NAME) != "") {
			getUpvotedLinksByTypeSelf(localStorage.getItem(FB_CONSTANT_NAME),FB);
		}
		if (localStorage.getItem(TW_CONSTANT_NAME) != null
				&& localStorage.getItem(TW_CONSTANT_NAME) != "") {
			getUpvotedLinksByTypeSelf(localStorage.getItem(TW_CONSTANT_NAME),TW);
		}
		if (localStorage.getItem(GAPI_CONSTANT_NAME) != null
				&& localStorage.getItem(GAPI_CONSTANT_NAME) != "") {
			getUpvotedLinksByTypeSelf(localStorage.getItem(GAPI_CONSTANT_NAME),GAPI);
		}
		
		addiFrames(true, true, true);
		addListener();
		if (!isIdentityDivCreated) {
			createIdentityDiv();
		}

		getNonFriendLinkUpVotes();

		//	
	}
}

function mergeJSON(sessionMap, jsonString) {
	var tempString = JSON.parse(sessionMap);
	var json = (jsonString);
	var sessionJson = JSON.parse(sessionMap);
	var i = 0;
	for ( var key in json) {
		i = 0;
		var flag = true;
		for ( var sessionKey in sessionJson) {
			if (key == sessionKey) {
				console.log(key + ' ' + sessionKey);
				flag = false;
				break;
			}
		}
		if (flag) {
			tempString[key] = json[key];
		}
	}
	tempString = deleteOldEntriies(tempString, 200);

	return tempString;
}

function deleteOldEntriies(tempString, no) {
	var elements = JSON.stringify(tempString).split(',').length;
	var toBeDeleted = elements - no;
	if (toBeDeleted > 0) {
		var i = 0;
		for ( var key in tempString) {
			if (i > toBeDeleted)
				break;
			console.log(tempString[key]);
			delete tempString[key];
			i++;

		}

	}
	return tempString;
	// console.log(tempString);
	// alert(JSON.stringify(tempString).split(',').length);
	// alert(JSON.stringify(tempString).split(','));

}

function getUpvotedLinksByType(type) {
	if (type == GAPI) {
		isGapiLocalStoreAvailable = true;
		getWowFactor(localStorage.getItem(GAPI_CONSTANT_NAME));
		getUpVotesLinks(localStorage.getItem(GAPI_CONSTANT_NAME), 'gmail');
	}
	if (type == FB) {
		isFbLocalStoreAvailable = true;
		getWowFactor(localStorage.getItem(FB_CONSTANT_NAME));
		getUpVotesLinks(localStorage.getItem(FB_CONSTANT_NAME), 'facebook');
	}
	if (type == TW) {
		isTwLocalStoreAvailable = true;
		getWowFactor(localStorage.getItem(TW_CONSTANT_NAME));
		getUpVotesLinks(localStorage.getItem(TW_CONSTANT_NAME), 'twitter');
	}

}
function getUpvotedLinksByTypeSelf(user,type) {
	if (type == GAPI) {
		isGapiSelfStoreAvailable = true;
		getUpVotesLinks(localStorage.getItem(FB_CONSTANT_NAME), 'selfLike');
	}
	if (type == FB) {
		isFbSelfStoreAvailable = true;
		getUpVotesLinks(localStorage.getItem(TW_CONSTANT_NAME), 'selfLike');
	}
	if (type == TW) {
		isTwSelfStoreAvailable = true;
		getUpVotesLinks(localStorage.getItem(GAPI_CONSTANT_NAME), 'selfLike');
	}

}
function addListener() {
	localStorage.setItem(GAPI_CONSTANT_FRIENDS, "");
	localStorage.setItem(FB_CONSTANT_FRIENDS, "");
	localStorage.setItem(TW_CONSTANT_FRIENDS, "");
	localStorage.setItem(GAPI_CONSTANT_NAME, "");
	localStorage.setItem(FB_CONSTANT_NAME, "");
	localStorage.setItem(TW_CONSTANT_NAME, "");

	window.addEventListener('message', function(e) {
		linksArrayCheckAndInit();
		var str = e.data + "";
		if (str.indexOf('twitt-name') > -1) {
			isTwAvailable = true;
			twitterName = str.substring(str.indexOf('twitt-name') + 10,
					str.length);
			console.log('ISHUUUUUUUUUUUUUUUUUUUUUUUUUgoogleUUUUUU '
					+ twitterName);
			storeQuery(twitterName, query);
			var name = twitterName;
			localStorage.setItem(TW_CONSTANT_NAME, name)
			if(!isTwSelfStoreAvailable)
			{
//				storeFriends()
				getUpVotesLinks( name , 'selfLike');
			}
		}
		if (str.indexOf('gapi-name') > -1) {
			isGapiAvailable = true;
			gapiName = str.substring(str.indexOf('gapi-name') + 9, str.length);
			localStorage.setItem(GAPI_CONSTANT_NAME, gapiName);
			storeQuery(gapiName, query);
			console.log('GAPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPI ' + '"friends":["' + gapiName + '"]');
			var name = gapiName;
			if(!isGapiSelfStoreAvailable)
			{
				getUpVotesLinks(name , 'selfLike');
			}
		}
		if (str.indexOf('fbName') > -1) {
			isFbAvailable = true;
			fbUserName = str.substring(str.indexOf('fbName') + 6, str.length);

			console.log('FBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB '
					+ fbUserName);
		}
		if (str.indexOf('status') > -1) {
			console.log(str);
			if (str.search(-1) > -1) {
				stat = -1
				console.log('Please log in');
			}
			if (str.search(0) > -1) {
				stat = 0;
				console.log('Please allow the app');
			}

		}
		if (str.indexOf('gapi-frnds') > -1) {
			gapiFriends = str.substring(str.indexOf('gapi-frnds^') + 11,
					str.length);
			storeFriends(gapiFriends,gapiName);
			localStorage.setItem(GAPI_CONSTANT_FRIENDS, gapiFriends);
			if (!isGapiLocalStoreAvailable) {
				getWowFactor(gapiName);
				getUpVotesLinks(gapiName, 'gmail');
			}
		} else if (str.indexOf('twitt-frnds^') > -1) {
			twitterFriends = str.substring(str.indexOf('twitt-frnds^') + 12,
					str.length);
			storeFriends(twitterFriends,twitterName);
			localStorage.setItem(TW_CONSTANT_FRIENDS, twitterFriends);
			if (!isTwLocalStoreAvailable) {
				getWowFactor(twitterName);
				getUpVotesLinks(twitterName, 'twitter');
			}
		} else if (str.search('friends') > -1) {
			fbFriends = e.data;
			localStorage.setItem(FB_CONSTANT_FRIENDS, fbFriends);
			storeFriends(fbFriends,user);
			if (!isFbLocalStoreAvailable) {
				getWowFactor(user);
				getUpVotesLinks(user, 'facebook');
			}
		}
		if (str.search('user') > -1) {
			var userJSON = str.split('=');
			user = userJSON[1];
			storeQuery(user, query);
			localStorage.setItem(FB_CONSTANT_NAME, user );
			var name = user;
			if(!isFbSelfStoreAvailable)
			{
				getUpVotesLinks( name, 'selfLike');
			}
			// alert(user);
			// sendMessage('setUser=' + user);
		}

	});
}

function getWowFactor(user) {
	linksArrayCheckAndInit();
//	var tempFriends = (JSON.parse('{' + friends + '}').friends);
//	for (var i = 0; i < tempFriends.length; i++) {
//		var tmp = totalFriends.toString() + '';
//		if ((tmp.indexOf(tempFriends[i]) == -1) || tmp == '')
//			totalFriends.push(tempFriends[i]);
//
//	}
	sendWowRequest(user);
	// totalFriends=totalFriends+friends.toString();
	// alert(totalFriends +" ISHUUUUUUUU");
	// fdsvds
}

function sendWowRequest(friends) {
	// alert(links.toString() +" "+friends);
	linksArrayCheckAndInit();
//	var tempFriends = '"friends":[';
//	var friendsList = friends.toString().split(",");
//	for (var i = 0; i < friendsList.length; i++) {
//		if (i == 0)
//			tempFriends += '"' + friendsList[i] + '"';
//		else
//			tempFriends += ',"' + friendsList[i] + '"';
//	}
//	tempFriends += ']';
	sendAjaxWow('https://' + host + ':8443/extension/rest/extension/getWow',
			'{"links":[' + links.toString() + '],' + '"user":"'+user+'"'
					+ ',"site":"wow","query":"' + query + '" }');
}

function sendAjaxWow(url, data) {
	var req = createRequest(); // defined above
	// Create the callback:
	req.onreadystatechange = function() {
		if (req.readyState != 4)
			return; // Not there yet
		if (req.status != 201) {
			return;
		}
		var resp = req.responseText;
		// alert(resp);
		addTheDataToResultsFb(req.responseText);
	}
	req.open("POST", url, true);
	req.setRequestHeader("Content-Type", "application/json");
	req.send(data);
}

function showLinkStorage() {
	chrome.storage.local.get('links', function(result) {
		alert(result.links);
	});
}

function clearStorage() {
	// chrome.storage.local.set({
	// 'links' : '{}'
	// });
	localStorage.removeItem(GAPI_CONSTANT_FRIENDS);
	localStorage.removeItem(FB_CONSTANT_FRIENDS);
	localStorage.removeItem(TW_CONSTANT_FRIENDS);
	localStorage.removeItem(CONSTANT_STOREMAP);

}

function getUpVotesLinks(user, site) {
	if(user=='')
		{
			return;
		}
	sendAjaxLinkUpVotes('https://' + host
			+ ':8443/extension/rest/extension/getLinkUpvotes', '{"links":['
			+ links.toString() + '],"user":"' + user + '","site":"' + site + '" }');
}
function storeFriends(friends, name) {
	var url='https://' + host
	+ ':8443/extension/rest/extension/storeFriends';
	var data='{"user":"'
		+ name+ '",' + friends + ' }';
//	sendAjaxLinkUpVotes('https://' + host
//			+ ':8443/extension/rest/extension/storeFriends', '{"user":['
//			+ name+ '],' + friends + ',"site":"' + site + '" }');

	var req = createRequest(); // defined above
	// Create the callback:
	req.onreadystatechange = function() {
		if (req.readyState != 4)
			return; // Not there yet
		if (req.status != 201) {
			return;
		}
		var resp = req.responseText;

		addTheDataToResultsFb(req.responseText);
	}
	req.open("POST", url, true);
	req.setRequestHeader("Content-Type", "application/json");
	req.send(data);

}

function createRequest() {
	var result = null;
	if (window.XMLHttpRequest) {
		// FireFox, Safari, etc.
		result = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// MSIE
		result = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
	}
	return result;
}

function insertAfter(referenceNode, newNode) {
	referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

function addTheDataToResultsFb(res) {

	var map = JSON.parse(res);
	// alert(res);
	var site = map["site"];
	console.log(isFbApplied + '' + isGapiApplied + isTwApplied);

	var x = document.getElementsByTagName("h3");

	for (var i = 0; i < x.length; i++) {
		var a = x[i].innerHTML;

		if (a.indexOf('href') > -1) {

			var start = a.indexOf('href="') + 6;
			var end = a.substring(start, a.length).indexOf('" ') + start;
			var link = a.substring(start, end);

			if (link.indexOf('http') > -1 && link.indexOf('adurl=') == -1) {
				link = normalizeLink(link);

				var el = document.getElementById("frinser_di_" + i);
				if (el == undefined) {
					el = document.createElement("div");
					insertAfter(x[i], el);
					el.id = "frinser_di_" + i;
				}

				if (map[link] != undefined)

				{
					console.log("addTheDataToResultsF : link : " + link
							+ " map[link] : " + map[link]);
					if (site == 'facebook'||site == 'twitter'||site == 'gmail') {
						isFbApplied = true;
						if (el.innerHTML.indexOf(site ) > -1) {
							console.log("ADRE");
						} else
							{
							if(el.innerHTML.indexOf('totalNo')==-1)
							{el.innerHTML = '<a  class="iconGlobe"><img src="https://'
									+ host
									+ ':8443/extension/2327917647-google-icon.png" height="20px" width="20px"/><span class="notification-count totalNo'+i+' '+site+'">'
									+ map[link] + '</span></a>' + el.innerHTML;
							}
							else
								{
								 el.getElementsByClassName('totalNo'+i)[0].innerHTML=+map[link];
								 el.getElementsByClassName('totalNo'+i)[0].className=el.getElementsByClassName('totalNo'+i)[0].className+' '+site;
								}
							}
					}
					else if (site == _wow) {
						if (el.innerHTML.indexOf('wow-count') > -1) {
							document.getElementById(link).innerHTML = map[link];
						} else if (map[link] > 0) {
							el.innerHTML = el.innerHTML
									+ '<span class="wow-count" id= "' + link
									+ '">' + map[link] + '</span>';
						}
					} else if (site == _all) {
						gotNonFriendLinkUpVotes = true;
						if (el.innerHTML.indexOf('all-class') > -1) {
							console.log("ADRE");
						} else if (map[link] > 0) {
							if (x.length > 0) { /* h3 tags have been populated */
								getLinksMap();
							}

							el.innerHTML = '<a  class="iconGlobe"><img src="https://'
									+ host
									+ ':8443/extension/group.png" height="20px" width="20px"/><span class="notification-count all-class">'
									+ map[link] + '</span></a>' + el.innerHTML;
						}
					} else if (site == 'selfLike') {
						gotNonFriendLinkUpVotes = true;
						if (el.innerHTML.indexOf('self-like') > -1) {
							console.log("ADRE");
						} else if (map[link] > 0) {
							el.innerHTML = '<a  class="iconGlobe"><img src="https://'
									+ host
									+ ':8443/extension/tick.png" height="20px" width="20px"/><span class="self-like"></span></a>'
									+ el.innerHTML;
						}
					}

				} else {
					if (site == 'facebook'||site == 'twitter'||site == 'gmail') {
						isFbApplied = true;
						if (el.innerHTML.indexOf(site ) > -1) {
							console.log("ADRE");
						} else
							{if(el.innerHTML.indexOf('totalNo')==-1)
							{el.innerHTML = '<a  class="iconGlobe"><img src="https://'
									+ host
									+ ':8443/extension/2327917647-google-icon.png" height="20px" width="20px"/><span class="notification-count totalNo'+i+' '+site+'">'
									+ 0 + '</span></a>' + el.innerHTML;
							}
							else
								{
								 el.getElementsByClassName('totalNo'+i)[0].innerHTML=parseInt(el.getElementsByClassName('totalNo'+i)[0].innerHTML)+0;
								 el.getElementsByClassName('totalNo'+i)[0].className=el.getElementsByClassName('totalNo'+i)[0].className+' '+site;
								}
							}
					}  
					else if (site == _wow) {
						/*
						 * if (el.innerHTML.indexOf('wow-count') > -1) {
						 * document.getElementById(link).innerHTML='NA'; } else
						 * el.innerHTML = '<span class="wow-count" id=
						 * "'+link+'">' +'NA' + '</span>' + el.innerHTML;
						 */
					} else if (site == _all) {
						isNonFriendApplied = true;
						if (el.innerHTML.indexOf('all-class') > -1) {
							console.log("ADRE");
						} else {
							if (x.length > 0) { /* h3 tags have been populated */
								getLinksMap();
							}

							el.innerHTML = '<a  class="iconGlobe"><img src="https://'
									+ host
									+ ':8443/extension/group.png" height="20px" width="20px"/><span class="notification-count all-class">'
									+ 0 + '</span></a>' + el.innerHTML;
						}
					}

				}

			}
		}// x[i].appendChild(a);
	}

	var y = document.getElementsByClassName("wow-count");
	for (var j = 0; j < y.length; j++) {
		y[j].style.fontWeight = 'bold';
		y[j].style.fontSize = "18px";
		y[j].style.color = "#0000A0";
	}
}

function storeQuery(user, query) {
	var url = 'https://' + host + ':8443/extension/rest/extension/storeQuery';
	var payload = '{"link":"' + query + '","user":"' + user + '" }';
	var req = createRequest(); // defined above
	// Create the callback:
	req.onreadystatechange = function() {
		if (req.readyState != 4)
			return; // Not there yet
		if (req.status != 201) {
			return;
		}
		var resp = req.responseText;
	}
	req.open("POST", url, true);
	req.setRequestHeader("Content-Type", "application/json");
	req.send(payload);
}

function sendAjaxLinkUpVotes(url, data) {
	var req = createRequest(); // defined above
	// Create the callback:
	req.onreadystatechange = function() {
		if (req.readyState != 4)
			return; // Not there yet
		if (req.status != 201) {
			return;
		}
		var resp = req.responseText;

		addTheDataToResultsFb(req.responseText);
	}
	req.open("POST", url, true);
	req.setRequestHeader("Content-Type", "application/json");
	req.send(data);
}

function getLinksMap() {
	links=[];
	var x = document.getElementsByTagName("h3");

	if (x.length == 0) {
		isScriptCalled = false;
		console.log("h3 srg div not created yet");
		// return false;
	} else {
		console.log("h3 srg div CREATED: " + x.length);
		
		query =document.getElementsByName("q")[0].value;// document.getElementById("gbqfq").value;
		
		for (var i = 0; i < x.length; i++) {
			var a = x[i].innerHTML;
			if (a.indexOf('href') > -1) {

				var start = a.indexOf('href="') + 6;
				var end = a.substring(start, a.length).indexOf('" ') + start;
				var link = a.substring(start, end);
				if (link.indexOf('http') > -1) { // x[i].innerHTML= "<img
					link = normalizeLink(link);
					if (link.search('adurl=') == -1) {
						links.push('"' + link + '"');
						storeLinks.push(link);
					}
				}
			}// x[i].appendChild(a);

		}

		var linksString = localStorage.getItem(CONSTANT_STOREMAP);
		if (linksString == null) {
			linksString = '';
		}
		for (var i = 0; i < storeLinks.length; i++) {
			if (contains(linksString, storeLinks[i]) != 'false')
				continue;
			if (linksString == '' && i == 0) {
				linksString += storeLinks[i] + '~' + query;
			} else {
				linksString += ',' + storeLinks[i] + '~' + query;
			}
		}
		if (linksString.split(',').length > 40) {
			var linksArray = linksString.split(',');
			linksArray.splice(0, linksString.split(',').length - 40);
			linksString = linksArray.toString();
		}
		console.log("LINKS STRING " + linksString)
		localStorage.setItem(CONSTANT_STOREMAP, linksString);
		// var jsonString={};
		// for(var i=0;i<storeLinks.length;i++)
		// {
		// jsonString[storeLinks[i]] = query;
		// }
		//
		// sessionMap=localStorage.getItem(CONSTANT_STOREMAP);
		// try {
		// JSON.parse(sessionMap);
		// }
		// catch(err) {
		// localStorage.removeItem(CONSTANT_STOREMAP );
		// sessionMap=null;
		// }
		// //alert(JSON.stringify(sessionMap).split(','));
		// if(sessionMap!=null&&sessionMap!='')
		// {
		// if(sessionMap.indexOf('undefined')>-1)
		// {
		// localStorage.removeItem(CONSTANT_STOREMAP );
		// }
		// jsonString= mergeJSON( (sessionMap),jsonString);
		// }
		// localStorage.setItem(CONSTANT_STOREMAP,JSON.stringify(jsonString) );
		// console.log( JSON.stringify(jsonString));

		chrome.storage.local.set({
			'links' : linksString
		});
		storeLinks = [];
		return true;
	}
}

function contains(linkString, contains) {
	var linksArray = linkString.split(',');
	for (var i = 0; i < linksArray.length; i++) {
		if (linksArray[i].split('~')[0] == contains)
			return linksArray[i].split('~')[1];
	}
	return 'false';
}

function addiFrames(fb, tw, gm) {

	// checkLoginState();
	var x = document.getElementsByTagName("body");
	if (fb) {
		if ((document.getElementById("frame") == undefined)
				|| (document.getElementById("frame") == null)) {
			/* do nothing as iframe does not exist yet */
		} else {
			x[0].removeChild(document.getElementById("frame"));
		}
		var s = document.getElementsByTagName('body')[0];
		var g = document.createElement('iframe');
		g.src = "https://softctrl.in/public/popup.html";
		g.id = 'frame';
		g.height = '0px';
		g.width = '0px';
		g.style.display = 'none';
		document.body.appendChild(g);
		document.getElementById('frame').hidden = true;
	}
	if (tw) {
		if ((document.getElementById("frame2") == undefined)
				|| (document.getElementById("frame2") == null)) {
			/* do nothing as iframe does not exist yet */
		} else {
			x[0].removeChild(document.getElementById("frame2"));
		}
		var g = document.createElement('iframe');
		g.src = "https://" + softhost + "/twitteroauth-master/index.php";
		g.height = '0px';
		g.width = '0px';
		g.id = 'frame2';
		g.style.display = 'none';
		g.target = '_top';
		document.body.appendChild(g);
		document.getElementById('frame2').hidden = true;
	}
	if (gm) {
		if ((document.getElementById("frame3") == undefined)
				|| (document.getElementById("frame3") == null)) {
			/* do nothing as iframe does not exist yet */
		} else {
			x[0].removeChild(document.getElementById("frame3"));
		}
		var g = document.createElement('iframe');
		g.src = "https://softctrl.in/public/gapi.html";
		g.height = '0px';
		g.width = '0px';
		g.id = 'frame3';
		g.style.display = 'none';
		g.target = '_top';
		document.body.appendChild(g);
		document.getElementById('frame3').hidden = true;
	}

}

function normalizeLink(link) {
	if (link.indexOf('http') > -1) { // x[i].innerHTML= "<img
		link = link.substring(link.indexOf('//') + 2, link.length);
		if (link.indexOf('www') > -1)
			link = link.substring(link.indexOf('www.') + 4, link.length);
	}
	return link;

}

function getNonFriendLinkUpVotes() {
	sendAjaxLinkUpVotes('https://' + host
			+ ':8443/extension/rest/extension/getNonFriendLinkUpvotes',
			'{"links":[' + links.toString() + '],"site":"' + _all + '" }');
}